<template>
  <div class="vice-president-approval-page">
    <div class="wrap">
      <!-- 顶部步骤条 -->
      <StepBar :steps="steps" :current-step="5" />

      <div class="content">
        <!-- 左侧：基本信息、申请信息、解除记录、账单清算 -->
        <div class="left">
          <!-- 基本信息 -->
          <div class="card">
            <div class="card-title">基本信息</div>
            <el-descriptions :column="2" border label-class-name="desc-label" class="desc">
              <el-descriptions-item label="单据编号">{{ formData.elderlyNo }}</el-descriptions-item>
              <el-descriptions-item label="老人姓名">{{ formData.elderlyName }}</el-descriptions-item>
              <el-descriptions-item label="老人身份证号">{{ formData.elderlyIdCard }}</el-descriptions-item>
              <el-descriptions-item label="联系方式">{{ formData.contact }}</el-descriptions-item>
              <el-descriptions-item label="费用期限">{{ formData.feePeriod }}</el-descriptions-item>
              <el-descriptions-item label="护理等级">{{ formData.careLevel }}</el-descriptions-item>
              <el-descriptions-item label="入住床位">{{ formData.bedNumber }}</el-descriptions-item>
              <el-descriptions-item label="签约合同">
                {{ formData.contract }}
                <el-button link type="primary" size="small" style="margin-left: 8px" @click="viewContract">查看</el-button>
              </el-descriptions-item>
              <el-descriptions-item label="养老顾问">{{ formData.consultant }}</el-descriptions-item>
              <el-descriptions-item label="护理员">{{ formData.caregiver }}</el-descriptions-item>
            </el-descriptions>
          </div>

          <!-- 申请信息 -->
          <div class="card">
            <div class="card-title">申请信息</div>
            <el-descriptions :column="2" border label-class-name="desc-label" class="desc">
              <el-descriptions-item label="退住日期">{{ formData.checkoutDate }}</el-descriptions-item>
              <el-descriptions-item label="退住原因">{{ formData.checkoutReason }}</el-descriptions-item>
              <el-descriptions-item label="备注" :span="2">
                {{ formData.remark }}
              </el-descriptions-item>
              <el-descriptions-item label="申请人">{{ formData.applicantName }}</el-descriptions-item>
              <el-descriptions-item label="申请时间">{{ formData.submitTime }}</el-descriptions-item>
            </el-descriptions>
          </div>

          <!-- 解除记录 -->
          <div class="card">
            <div class="card-title">解除记录</div>
            <el-descriptions :column="2" border label-class-name="desc-label" class="desc">
              <el-descriptions-item label="提交人">{{ formData.terminationSubmitter }}</el-descriptions-item>
              <el-descriptions-item label="解除日期">{{ formData.terminationDate }}</el-descriptions-item>
              <el-descriptions-item label="解除协议" :span="2">
                {{ formData.terminationAgreement }}
                <el-button link type="primary" size="small" style="margin-left: 8px" @click="viewTermination">查看</el-button>
              </el-descriptions-item>
            </el-descriptions>
          </div>

          <!-- 完成账单清算 -->
          <div class="card bill-settlement-card">
            <div class="card-title">完成账单清算</div>
            
            <div class="info-banner">
              <el-icon color="#409eff" style="margin-right: 8px;"><InfoFilled /></el-icon>
              需核对应退、欠费账单和杂费录退款吃，方可完成账单办理
            </div>

            <!-- 1. 应退 -->
            <div class="bill-section" v-if="billData.refund.items.length > 0">
              <div class="section-header">
                <span class="section-number">1</span>
                <span class="section-title">应退</span>
                <span class="section-amount">待扣：{{ billData.refund.items.length }}</span>
                <span class="section-total">小计：{{ refundTotal }}元</span>
              </div>
              
              <div v-for="(item, index) in billData.refund.items" :key="index" class="bill-item">
                <div class="bill-row">
                  <span class="label">账单编号：</span>
                  <el-link type="primary" v-if="item.billNo !== '暂无'">{{ item.billNo }}</el-link>
                  <span v-else style="color: #999;">{{ item.billNo }}</span>
                  <el-button type="primary" link size="small" style="margin-left: 10px;" v-if="item.billNo !== '暂无'">月度账单</el-button>
                </div>
                <div class="bill-row">
                  <span class="label">账单月份：</span>
                  <span>{{ item.month }}</span>
                  <span class="label ml-60">可退金额：</span>
                  <span>{{ item.availableAmount }}元</span>
                </div>
                <div class="bill-row">
                  <span class="label">实缴天数：</span>
                  <span>{{ item.actualDays }} 天</span>
                  <span class="label ml-60">退款天数：</span>
                  <span>{{ item.refundDays }} 天</span>
                </div>
                <div class="bill-row">
                  <span class="label">实退金额：</span>
                  <span class="value-highlight">{{ item.amount }}元</span>
                  <span class="label ml-60" v-if="item.note">调整备注：</span>
                  <span v-if="item.note">{{ item.note }}</span>
                </div>
              </div>
            </div>

            <!-- 2. 欠费 -->
            <div class="bill-section" v-if="billData.arrears.items.length > 0">
              <div class="section-header">
                <span class="section-number">2</span>
                <span class="section-title">欠费</span>
                <span class="section-amount">待扣：{{ sortedArrearsItems.length }}</span>
                <span class="section-total">小计：{{ calculateArrearsTotal }}元</span>
              </div>
              
              <div v-for="(item, index) in sortedArrearsItems" :key="index" class="bill-item">
                <div class="bill-row">
                  <span class="label">账单编号：</span>
                  <el-link type="primary">{{ item.billNo }}</el-link>
                  <el-button type="primary" link size="small" style="margin-left: 10px;">月度账单</el-button>
                </div>
                <div class="bill-row">
                  <span class="label">账单月份：</span>
                  <span>{{ item.month }}</span>
                  <span class="label ml-60">应付金额：</span>
                  <span>{{ item.amount }}元</span>
                </div>
              </div>
            </div>

            <!-- 3. 杂费 -->
            <div class="bill-section">
              <div class="section-header">
                <span class="section-number">3</span>
                <span class="section-title">杂费</span>
                <span class="section-total">小计：{{ miscFees }}元</span>
              </div>
              
              <div class="misc-fee-content">
                <div class="fee-row">
                  <span class="label">可退押金：</span>
                  <span class="value">{{ billData.misc.deposit }} 元</span>
                </div>
                <div class="fee-row">
                  <span class="label">实退金额：</span>
                  <span class="value-highlight">{{ billData.misc.deposit }} 元</span>
                  <span class="label ml-60" v-if="billData.misc.depositNote">调整备注：</span>
                  <span v-if="billData.misc.depositNote">{{ billData.misc.depositNote }}</span>
                </div>
                <div class="fee-row">
                  <span class="label">押金数：</span>
                  <span class="value">{{ billData.misc.deposit }} 元</span>
                </div>
                <div class="fee-row" style="margin-top: 15px; padding-top: 15px; border-top: 1px dashed #e0e0e0;">
                  <span class="label">杂费金额：</span>
                  <el-input-number v-model="miscFees" :precision="2" :step="100" :min="0" class="amount-input" />
                </div>
              </div>
            </div>

            <!-- 合计 -->
            <div class="total-banner">
              <el-icon color="#f56c6c" style="margin-right: 8px;"><WarningFilled /></el-icon>
              合计应收金额 = 应退 - 欠费 + 杂费 = {{ calculateTotal }}元
            </div>
          </div>
        </div>

        <!-- 右侧：审批结果、操作记录 -->
        <div class="right">
          <!-- 审批结果 -->
          <div class="card">
            <div class="card-title">审批结果</div>
            <div class="result-group">
              <div class="label"><span class="required">*</span>审批结果</div>
              <el-radio-group v-model="approvalResult">
                <el-radio label="pass">审批通过</el-radio>
                <el-radio label="reject">审批拒绝</el-radio>
              </el-radio-group>
            </div>
            <div class="result-group">
              <div class="label"><span class="required">*</span>审批意见</div>
              <el-input
                v-model="approvalComment"
                type="textarea"
                :rows="5"
                placeholder="请输入"
                maxlength="200"
                show-word-limit
              />
            </div>
          </div>

          <!-- 操作记录 -->
          <div class="card">
            <div class="card-title">操作记录</div>
            <div class="timeline">
              <div class="timeline-item">
                <div class="timeline-icon">
                  <el-icon color="#67c23a"><CircleCheck /></el-icon>
                </div>
                <div class="timeline-content">
                  <div class="timeline-title">发起申请-申请退住</div>
                  <div class="timeline-detail">
                    <span class="timeline-user">{{ formData.applicantName }}</span>
                    <el-tag type="success" size="small">已发起</el-tag>
                  </div>
                  <div class="timeline-time">{{ formData.submitTime }}</div>
                </div>
              </div>

              <div class="timeline-item">
                <div class="timeline-icon">
                  <el-icon color="#67c23a"><CircleCheck /></el-icon>
                </div>
                <div class="timeline-content">
                  <div class="timeline-title">(待处理)审批-申请审批</div>
                  <div class="timeline-detail">
                    <span class="timeline-user">退住审批员</span>
                    <el-tag type="success" size="small">已通过</el-tag>
                  </div>
                  <div class="current-step">这是当前审批处</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部操作按钮 -->
      <div class="footer-actions">
        <el-button @click="handleBack">返回</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { CircleCheck, InfoFilled, WarningFilled } from '@element-plus/icons-vue'
import StepBar from '@/components/StepBar/index.vue'
import { getCheckoutApplicationDetail } from '@/api/system/approval'
import { getContractByElderlyId, submitVicePresidentApproval } from '@/api/system/out_management'
import { updateTasks } from '@/api/system/tasks'

const router = useRouter()
const route = useRoute()

// 步骤条数据
const steps = ['申请退住', '申请审批', '解除合同', '调整账单', '账单审批', '退住审批', '费用清算']

// 表单数据
const formData = reactive({
  // 基本信息
  elderlyNo: '',
  elderlyName: '',
  elderlyIdCard: '',
  contact: '',
  feePeriod: '',
  careLevel: '',
  bedNumber: '',
  contract: '',
  consultant: '',
  caregiver: '',
  // 申请信息
  checkoutDate: '',
  checkoutReason: '',
  remark: '',
  applicantName: '',
  submitTime: '',
  // 解除记录
  terminationSubmitter: '',
  terminationDate: '',
  terminationAgreement: ''
})

// 审批表单
const approvalResult = ref('pass')
const approvalComment = ref('')

// ✅ 账单数据（从第五步传递过来）
const billData = reactive({
  // 应退卡片数据
  refund: {
    items: []
  },
  // 欠费卡片数据
  arrears: {
    items: []
  },
  // 杂费卡片数据
  misc: {
    deposit: 0,
    depositNote: ''
  },
  // 计算出的总金额
  totalAmount: '0.00'
})

// ✅ 老人余额信息（balance表数据）
const balanceInfo = reactive({
  elderlyId: null,
  depositBalance: 0,      // 押金余额
  prepaymentBalance: 0,   // 预交款余额
  totalBalance: 0         // 总余额
})

// 欠费项目 - 保持向后兼容
const arrearsItems = ref([])

// 杂费（可编辑）
const miscFees = ref(0)

// 计算应退总额
const refundTotal = computed(() => {
  if (!billData.refund.items || billData.refund.items.length === 0) {
    return '0.00'
  }
  const total = billData.refund.items.reduce((sum, item) => {
    return sum + (parseFloat(item.amount) || 0)
  }, 0)
  return total.toFixed(2)
})

// 计算欠费总计
const calculateArrearsTotal = computed(() => {
  if (!billData.arrears.items || billData.arrears.items.length === 0) {
    return '0.00'
  }
  return billData.arrears.items.reduce((sum, item) => sum + parseFloat(item.amount || 0), 0).toFixed(2)
})

// 计算总计（应退 - 欠费 + 杂费）
const calculateTotal = computed(() => {
  const refund = parseFloat(refundTotal.value || 0)
  const arrears = parseFloat(calculateArrearsTotal.value || 0)
  const misc = parseFloat(miscFees.value || 0)
  // 公式：应退 - 欠费 + 杂费
  return (refund - arrears + misc).toFixed(2)
})

// 倒序排列的欠费项目
const sortedArrearsItems = computed(() => {
  if (!billData.arrears.items || billData.arrears.items.length === 0) {
    return []
  }
  return [...billData.arrears.items].reverse()
})

// 页面加载时获取数据
onMounted(async () => {
  console.log('=== 副院长审批退住页面加载 ===')
  console.log('Route query:', route.query)
  
  const businessId = route.query.id
  console.log('业务ID:', businessId)
  
  if (!businessId) {
    ElMessage.warning('缺少业务ID参数')
    return
  }
  
  // ✅ 参数验证 - 改为警告而不是阻止页面加载
  if (!route.query.ptid) {
    ElMessage.warning('待办任务ID为空，页面可能无法正常提交！')
    console.warn('⚠️ 页面加载警告：ptid参数为空')
  }

  if (!route.query.taskId) {
    ElMessage.warning('工作流任务ID为空，页面可能无法正常提交！')
    console.warn('⚠️ 页面加载警告：taskId参数为空')
  }
  
  try {
    // 1. 获取退住申请详情
    console.log('开始查询退住申请详情...')
    const checkoutRes = await getCheckoutApplicationDetail(businessId)
    console.log('退住申请详情响应:', checkoutRes)
    
    if (checkoutRes.code === 200 && checkoutRes.data) {
      const appData = checkoutRes.data
      console.log('退住申请数据:', appData)
      
      // 填充基本信息（从退住申请中获取）
      formData.elderlyNo = appData.checkOutNo || 'TZ' + businessId
      formData.elderlyName = appData.elderlyName || ''
      formData.elderlyIdCard = appData.elderlyIdCard || ''
      formData.contact = appData.elderlyContact || ''
      formData.careLevel = appData.careLevel || ''
      formData.bedNumber = appData.bedNumber || ''
      formData.contract = appData.contractName || ''
      formData.consultant = appData.caregiverName || ''
      formData.caregiver = appData.caregiverName || ''
      
      // 费用期限
      if (appData.feeStartDate && appData.feeEndDate) {
        formData.feePeriod = `${appData.feeStartDate} - ${appData.feeEndDate}`
      }
      
      // 填充申请信息
      formData.checkoutDate = appData.checkOutDate || ''
      formData.checkoutReason = appData.checkOutReason || ''
      formData.remark = appData.remark || ''
      formData.applicantName = appData.creatorName || '未知申请人'
      formData.submitTime = appData.createTime || ''
      
      console.log('基本信息已填充:', {
        elderlyName: formData.elderlyName,
        consultant: formData.consultant,
        caregiver: formData.caregiver
      })
      
      console.log('申请信息已填充:', {
        checkoutDate: formData.checkoutDate,
        checkoutReason: formData.checkoutReason,
        applicantName: formData.applicantName
      })
      
      // 2. 如果有老人ID，获取合同信息（主要用于解除记录）
      if (appData.elderlyId) {
        console.log('查询老人合同信息, elderlyId:', appData.elderlyId)
        const contractRes = await getContractByElderlyId(appData.elderlyId)
        console.log('合同信息响应:', contractRes)
        
        if (contractRes.code === 200 && contractRes.data) {
          const contractData = contractRes.data
          console.log('合同数据:', contractData)
          
          // 填充解除记录
          if (contractData.terminationSubmitter) {
            // 解除提交人昵称
            if (contractData.sysUser && contractData.sysUser.nickName) {
              formData.terminationSubmitter = contractData.sysUser.nickName
            } else {
              formData.terminationSubmitter = '用户' + contractData.terminationSubmitter
            }
          }
          
          if (contractData.terminationTime) {
            formData.terminationDate = contractData.terminationTime
          }
          
          if (contractData.terminationAgreement) {
            formData.terminationAgreement = contractData.terminationAgreement
          }
          
          console.log('解除记录已填充:', {
            terminationSubmitter: formData.terminationSubmitter,
            terminationDate: formData.terminationDate,
            terminationAgreement: formData.terminationAgreement
          })
        }
      }
      
      console.log('=== 基本信息加载完成 ===')
    } else {
      ElMessage.error('查询退住申请详情失败')
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败：' + (error.message || '未知错误'))
  }
  
  // ✅ 读取第五步传递过来的账单数据
  console.log('=== 读取第五步传递的账单数据 ===')
  const storageKey = `bill_data_for_step6_${businessId}`
  console.log('尝试从sessionStorage读取:', storageKey)
  
  const savedBillData = sessionStorage.getItem(storageKey)
  if (savedBillData) {
    try {
      const parsedData = JSON.parse(savedBillData)
      console.log('从sessionStorage读取到的账单数据:', parsedData)
      
      // 更新账单数据
      if (parsedData.refund && parsedData.refund.items) {
        billData.refund.items = parsedData.refund.items
        console.log('✅ 应退数据已更新:', billData.refund.items)
      }
      
      if (parsedData.arrears && parsedData.arrears.items) {
        billData.arrears.items = parsedData.arrears.items
        arrearsItems.value = parsedData.arrears.items
        console.log('✅ 欠费数据已更新:', billData.arrears.items)
      }
      
      if (parsedData.misc) {
        billData.misc.deposit = parsedData.misc.deposit || 0
        billData.misc.depositNote = parsedData.misc.depositNote || ''
        // 初始化杂费输入框的值为押金金额
        miscFees.value = parsedData.misc.deposit || 0
        console.log('✅ 杂费数据已更新:', billData.misc)
        console.log('✅ 杂费输入框初始值:', miscFees.value)
      }
      
      if (parsedData.totalAmount) {
        billData.totalAmount = parsedData.totalAmount
        console.log('✅ 总金额已更新:', billData.totalAmount)
      }
      
      // ✅ 读取balance信息
      if (parsedData.balance) {
        balanceInfo.elderlyId = parsedData.balance.elderlyId || null
        balanceInfo.depositBalance = parsedData.balance.depositBalance || 0
        balanceInfo.prepaymentBalance = parsedData.balance.prepaymentBalance || 0
        balanceInfo.totalBalance = parsedData.balance.totalBalance || 0
        console.log('✅ Balance信息已更新:', balanceInfo)
      }
      
      console.log('=== 账单数据加载完成 ===')
      console.log('最终账单数据:', {
        refund: billData.refund,
        arrears: billData.arrears,
        misc: billData.misc,
        balance: balanceInfo,
        totalAmount: billData.totalAmount
      })
      
    } catch (parseError) {
      console.error('解析账单数据失败:', parseError)
      ElMessage.warning('账单数据加载失败，显示默认数据')
      
      // 使用默认数据
      initializeDefaultBillData()
    }
  } else {
    console.log('⚠️ sessionStorage中没有找到账单数据，使用默认数据')
    ElMessage.warning('未找到账单数据，显示默认数据')
    
    // 使用默认数据
    initializeDefaultBillData()
  }
  
  console.log('=== 页面数据加载完成 ===')
})

// 初始化默认账单数据
function initializeDefaultBillData() {
  console.log('初始化默认账单数据...')
  
  billData.refund.items = []
  
  billData.arrears.items = [
    { billNo: 'ZD204810101S000003', month: '2048-12', amount: 3000.00 },
    { billNo: 'ZD204810101S000002', month: '2048-11', amount: 2500.00 },
    { billNo: 'ZD204810101S000001', month: '2048-10', amount: 2000.00 }
  ]
  
  arrearsItems.value = billData.arrears.items
  
  billData.misc.deposit = 0
  billData.misc.depositNote = ''
  miscFees.value = 0
  
  billData.totalAmount = '0.00'
  
  console.log('默认账单数据已设置')
}

// 查看合同
const viewContract = () => {
  if (formData.contract) {
    ElMessage.info('查看合同文件：' + formData.contract)
  } else {
    ElMessage.warning('暂无合同文件')
  }
}

// 查看解除协议
const viewTermination = () => {
  if (formData.terminationAgreement) {
    ElMessage.info('查看解除协议：' + formData.terminationAgreement)
  } else {
    ElMessage.warning('暂无解除协议')
  }
}

// 返回
const handleBack = () => {
  // 返回到待办任务列表
  router.push('/xtgz/xtgz/tasks')
}

// 提交
const handleSubmit = async () => {
  // ✅ 参数验证 - 只验证业务ID，其他参数允许为空
  if (!route.query.id) {
    ElMessage.error('业务ID为空，无法提交！')
    console.error('❌ 提交失败：businessId参数为空')
    return
  }

  // 警告用户参数可能不完整
  if (!route.query.ptid || !route.query.taskId) {
    ElMessage.warning('页面参数不完整，提交可能失败！建议从待办任务列表重新进入。')
    console.warn('⚠️ 提交警告：参数不完整', {
      ptid: route.query.ptid,
      taskId: route.query.taskId
    })
  }

  // 验证审批意见
  if (!approvalComment.value.trim()) {
    ElMessage.warning('请填写审批意见！')
    return
  }

  const resultText = approvalResult.value === 'pass' ? '审批通过' : '审批拒绝'

  try {
    await ElMessageBox.confirm(
      `确认提交审批吗？\n审批结果：${resultText}\n审批意见：${approvalComment.value}`,
      '确认提交',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    // 准备提交数据
    const submitData = {
      businessId: route.query.id, // 业务ID
      taskId: route.query.taskId || '', // 工作流任务ID
      ptId: route.query.ptid || '', // 待办任务ID
      opinion: approvalComment.value, // 审批意见
      auditStatus: approvalResult.value === 'pass' ? 1 : 2, // 审核状态：1=通过，2=拒绝
      miscFees: miscFees.value // 杂费金额
    }

    console.log('=== 副院长审批提交 ===')
    console.log('提交数据:', submitData)
    console.log('业务ID:', submitData.businessId)
    console.log('审批结果:', approvalResult.value)
    console.log('审批意见:', approvalComment.value)
    console.log('杂费金额:', miscFees.value)

    // 调用后端API提交审批
    const response = await submitVicePresidentApproval(submitData)

    if (response.code === 200) {
      ElMessage.success('副院长审批已提交！')
      
      // ✅ 保存账单数据到sessionStorage，供第七步使用
      console.log('=== 保存账单数据到sessionStorage（第六步到第七步）===')
      const billDataForStep7 = {
        // 应退卡片数据
        refund: {
          items: billData.refund.items.map(item => ({
            billNo: item.billNo,
            month: item.month,
            availableAmount: item.availableAmount,
            actualDays: item.actualDays,
            refundDays: item.refundDays,
            amount: item.amount,
            note: item.note,
            status: item.status
          }))
        },
        // 欠费卡片数据
        arrears: {
          items: billData.arrears.items.map(item => ({
            billNo: item.billNo,
            month: item.month,
            amount: item.amount,
            status: item.status || '待支付'
          }))
        },
        // 杂费卡片数据
        misc: {
          deposit: billData.misc.deposit,
          depositNote: billData.misc.depositNote,
          miscFees: miscFees.value  // 第六步调整的杂费金额
        },
        // ✅ 老人余额信息（balance表数据）
        balance: {
          elderlyId: balanceInfo.elderlyId,
          depositBalance: balanceInfo.depositBalance,     // 押金余额
          prepaymentBalance: balanceInfo.prepaymentBalance, // 预交款余额
          totalBalance: balanceInfo.totalBalance           // 总余额
        },
        // 计算出的总金额
        totalAmount: calculateTotal.value,
        // 保存时间戳
        timestamp: new Date().getTime()
      }
      
      // 保存到sessionStorage（使用业务ID作为key的一部分）
      const storageKey = `bill_data_for_step7_${route.query.id}`
      sessionStorage.setItem(storageKey, JSON.stringify(billDataForStep7))
      console.log('账单数据已保存到sessionStorage（供第七步使用）:', storageKey)
      console.log('保存的数据:', billDataForStep7)
      
      // ✅ 调试：检查后端返回的参数
      console.log('=== 第六步后端返回参数检查 ===')
      console.log('response.data:', response.data)
      console.log('nextTaskId:', response.data?.nextTaskId)
      console.log('nextPtId:', response.data?.nextPtId)

      // ✅ 重写：使用最简单直接的方法更新状态
      console.log('=== 重写第六步状态更新逻辑 ===')
      console.log('待办任务ID:', submitData.ptId)
      
      // 方法1：直接调用后端API更新状态
      try {
        console.log('方法1：直接调用后端API更新状态')
        
        // 使用最简单的数据格式
        const simpleUpdateData = {
          id: submitData.ptId,
          isHandle: 1
        }
        
        console.log('简单更新数据:', simpleUpdateData)
        
        const updateResponse = await updateTasks(simpleUpdateData)
        console.log('更新响应:', updateResponse)
        
        if (updateResponse.code === 200) {
          console.log('✅ 方法1成功：第六步待办任务状态更新成功！')
          ElMessage.success('第六步待办任务状态已更新！')
        } else {
          console.error('❌ 方法1失败:', updateResponse.msg)
          throw new Error('方法1失败')
        }
        
      } catch (method1Error) {
        console.error('❌ 方法1异常:', method1Error)
        
        // 方法2：使用更简单的数据格式
        try {
          console.log('方法2：使用更简单的数据格式')
          
          const minimalUpdateData = {
            id: submitData.ptId,
            isHandle: 1,
            updateTime: new Date().getTime() // 使用时间戳
          }
          
          console.log('最小更新数据:', minimalUpdateData)
          
          const updateResponse2 = await updateTasks(minimalUpdateData)
          console.log('更新响应2:', updateResponse2)
          
          if (updateResponse2.code === 200) {
            console.log('✅ 方法2成功：第六步待办任务状态更新成功！')
            ElMessage.success('第六步待办任务状态已更新！')
          } else {
            console.error('❌ 方法2失败:', updateResponse2.msg)
            throw new Error('方法2失败')
          }
          
        } catch (method2Error) {
          console.error('❌ 方法2异常:', method2Error)
          
          // 方法3：只更新必要字段
          try {
            console.log('方法3：只更新必要字段')
            
            const essentialUpdateData = {
              id: submitData.ptId,
              isHandle: 1,
              status: 1
            }
            
            console.log('必要更新数据:', essentialUpdateData)
            
            const updateResponse3 = await updateTasks(essentialUpdateData)
            console.log('更新响应3:', updateResponse3)
            
            if (updateResponse3.code === 200) {
              console.log('✅ 方法3成功：第六步待办任务状态更新成功！')
              ElMessage.success('第六步待办任务状态已更新！')
            } else {
              console.error('❌ 方法3失败:', updateResponse3.msg)
              ElMessage.warning('副院长审批提交成功，但状态更新失败')
            }
            
          } catch (method3Error) {
            console.error('❌ 方法3异常:', method3Error)
            ElMessage.warning('副院长审批提交成功，但状态更新异常')
          }
        }
      }

      // 提交后跳转
      setTimeout(() => {
        if (approvalResult.value === 'pass') {
          // 审批通过：跳转到费用清算页面（步骤7）
          // ✅ 需要传递第七步所需的参数
          router.push({
            path: '/splccs/zdtzhtk',
            query: {
              id: route.query.id, // 业务ID
              taskId: response.data?.nextTaskId || '', // 第七步的工作流任务ID
              ptid: response.data?.nextPtId || '', // 第七步的待办任务ID
              step: 7,
              type: route.query.type || 1
            }
          })
        } else {
          // 审批拒绝：直接返回待办任务列表
          router.push({
            path: '/xtgz/xtgz/tasks'
          })
        }
      }, 1000)
    } else {
      ElMessage.error(response.msg || '提交失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('提交异常:', error)
      ElMessage.error('提交失败：' + (error.message || '未知错误'))
    }
  }
}
</script>

<style scoped lang="scss">
.vice-president-approval-page {
  min-height: 100%;
  background: linear-gradient(135deg, #e8f5e9 0%, #f1f8e9 50%, #fffde7 100%);
  padding: 20px;

  .wrap {
    max-width: 1400px;
    margin: 0 auto;
  }

  .content {
    display: flex;
    gap: 20px;
    margin-top: 20px;

    .left {
      flex: 1;
      display: flex;
      flex-direction: column;
      gap: 20px;
    }

    .right {
      width: 380px;
      display: flex;
      flex-direction: column;
      gap: 20px;
    }
  }

  .card {
    background: white;
    border-radius: 8px;
    padding: 24px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .card-title {
      font-size: 16px;
      font-weight: bold;
      color: #303133;
      margin-bottom: 20px;
      padding-bottom: 12px;
      border-bottom: 2px solid #e4e7ed;
    }
  }

  /* 描述列表 */
  .desc {
    :deep(.el-descriptions__label) {
      width: 120px;
      background-color: #fafafa;
    }
  }

  /* 账单清算卡片 */
  .bill-settlement-card {
    .info-banner {
      display: flex;
      align-items: center;
      background: #ecf5ff;
      border: 1px solid #d9ecff;
      border-radius: 4px;
      padding: 12px 16px;
      margin-bottom: 20px;
      font-size: 14px;
      color: #409eff;
    }

    .bill-section {
      margin-bottom: 24px;

      .section-header {
        display: flex;
        align-items: center;
        margin-bottom: 16px;
        padding: 12px;
        background: #f5f7fa;
        border-radius: 4px;

        .section-number {
          width: 24px;
          height: 24px;
          background: #f56c6c;
          color: white;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 14px;
          font-weight: bold;
          margin-right: 8px;
        }

        .section-title {
          font-size: 15px;
          font-weight: bold;
          color: #303133;
          margin-right: auto;
        }

        .section-amount {
          font-size: 14px;
          color: #f56c6c;
          margin-right: 16px;
        }

        .section-total {
          font-size: 14px;
          color: #f56c6c;
          font-weight: bold;
        }
      }

      .bill-item {
        padding: 16px;
        background: #fafafa;
        border-radius: 4px;
        margin-bottom: 12px;

        &:last-child {
          margin-bottom: 0;
        }
      }

      .bill-row {
        display: flex;
        align-items: center;
        margin-bottom: 12px;

        &:last-child {
          margin-bottom: 0;
        }

        .label {
          font-size: 14px;
          color: #606266;
          min-width: 80px;
        }

        .ml-60 {
          margin-left: 60px;
        }

        .amount-input {
          width: 200px;
        }
        
        .value-highlight {
          color: #f56c6c;
          font-weight: bold;
        }
      }
      
      /* 杂费内容样式 */
      .misc-fee-content {
        padding: 15px;
        background: #fafafa;
        border: 1px solid #e8e8e8;
        border-radius: 4px;
      }
      
      .fee-row {
        display: flex;
        align-items: center;
        margin-bottom: 12px;
        font-size: 13px;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .label {
          color: #666;
          min-width: 100px;
        }
        
        .value {
          color: #333;
          font-weight: 500;
        }
        
        .value-highlight {
          color: #f56c6c;
          font-weight: bold;
        }
        
        .ml-60 {
          margin-left: 60px;
        }
        
        .amount-input {
          width: 150px;
        }
      }
    }

    .total-banner {
      display: flex;
      align-items: center;
      background: #fef0f0;
      border: 1px solid #fde2e2;
      border-radius: 4px;
      padding: 12px 16px;
      margin-bottom: 20px;
      font-size: 14px;
      color: #f56c6c;
      font-weight: bold;
    }

  }

  /* 审批表单 */
  .result-group {
    margin-bottom: 20px;

    &:last-child {
      margin-bottom: 0;
    }

    .label {
      font-size: 14px;
      color: #333;
      margin-bottom: 10px;
      font-weight: 500;

      .required {
        color: #f56c6c;
        margin-right: 4px;
      }
    }

    :deep(.el-radio-group) {
      display: flex;
      gap: 20px;
    }
  }

  /* 时间轴 */
  .timeline {
    .timeline-item {
      display: flex;
      gap: 15px;
      margin-bottom: 25px;
      position: relative;

      &:last-child {
        margin-bottom: 0;
      }

      &:not(:last-child)::after {
        content: '';
        position: absolute;
        left: 11px;
        top: 35px;
        width: 2px;
        height: calc(100% + 10px);
        background: #e4e7ed;
      }

      .timeline-icon {
        width: 24px;
        height: 24px;
        flex-shrink: 0;
        font-size: 24px;
        position: relative;
        z-index: 1;
      }

      .timeline-content {
        flex: 1;

        .timeline-title {
          font-size: 14px;
          color: #303133;
          margin-bottom: 8px;
          font-weight: 500;
        }

        .timeline-detail {
          display: flex;
          align-items: center;
          gap: 10px;
          margin-bottom: 8px;

          .timeline-user {
            font-size: 13px;
            color: #606266;
          }
        }

        .timeline-time {
          font-size: 12px;
          color: #909399;
        }

        .current-step {
          font-size: 12px;
          color: #409eff;
          font-weight: bold;
        }
      }
    }
  }

  /* 底部操作按钮 */
  .footer-actions {
    margin-top: 24px;
    padding: 20px 0;
    text-align: center;
    display: flex;
    justify-content: center;
    gap: 16px;

    .el-button {
      min-width: 100px;
    }
  }
}
</style>

